package com.daykw.douyin.task;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.model.VideoAuth;
import com.daykw.douyin.model.VideoAuthSearch;
import com.daykw.douyin.utils.SpringContextHolder;

public class VideoAuthSearchThread extends Thread {

	private static Logger logger = Logger.getLogger(VideoAuthSearchThread.class);
	private NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
	private SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
	private SimpleDateFormat datefmt = new SimpleDateFormat("yyyyMMdd");

	@Override
	public void run() {

		try {

			List<VideoAuthSearch> list = dao.query(VideoAuthSearch.class, Cnd.where("status", "=", 0).limit(1, 5));

			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
			String cookie = dao.fetch("t_cookie", Cnd.where("name", "=", "13235801201")).getString("cookie");
			headers.put("Cookie", cookie);

			for (VideoAuthSearch v : list) {

				int page = 1;
				boolean b = true;
				page = v.getPage();
				do {
					String aurl = v.getUrl() + "?period=" + v.getPeriod() + "&tag="
							+ URLEncoder.encode(v.getTag(), "utf-8") + "&keyword=&datecode=" + v.getDatecode()
							+ "&page=" + page;
					String html = http.get(aurl, headers);

					if (page > 1) {
						html = "<table>" + html + "</table>";
						Document doc = Jsoup.parse(html);
						Elements awemelist = doc.select("tbody tr");
						for (Element tr : awemelist) {
							Elements tds = tr.select("td");
							Element name = tds.get(1);
							Element td3 = tds.get(3);
							Element td4 = tds.get(4);
							Element td5 = tds.get(5);
							Element td6 = tds.get(6);
							String fs = td3.text();
							String avg_like = td4.text();
							String avg_cmt = td5.text();
							String avg_rep = td6.text();
							Element urls = tds.get(7);
							String href = urls.select("a").first().attr("href");

							String dataid = href.substring(href.indexOf("=") + 1, href.indexOf("&"));
							this.saveData(dataid, href, name.text(), fs, avg_like, avg_cmt, avg_rep);

						}

					} else {
						Document doc = Jsoup.parse(html);
						Elements awemelist = doc.select("tbody tr");
						for (Element tr : awemelist) {
							Elements tds = tr.select("td");
							Element name = tds.get(1);
							Element td3 = tds.get(3);
							Element td4 = tds.get(4);
							Element td5 = tds.get(5);
							Element td6 = tds.get(6);
							String fs = td3.text();
							String avg_like = td4.text();
							String avg_cmt = td5.text();
							String avg_rep = td6.text();
							Element urls = tds.get(7);
							String href = urls.select("a").first().attr("href");

							String dataid = href.substring(href.indexOf("=") + 1, href.indexOf("&"));
							this.saveData(dataid, href, name.text(), fs, avg_like, avg_cmt, avg_rep);

						}
					}

					page++;

					if (page > 5) {
						b = false;
					}
					dao.update(
							VideoAuthSearch.class, Chain.make("update_time", new Date())
									.add("udate", Long.parseLong(fmt.format(new Date()))).add("page", page),
							Cnd.where("id", "=", v.getId()));
					logger.info("#########用户排行榜,第" + page + "页，" + v.getTag() + "下完，暂停5秒");
					Thread.sleep(5000);

				} while (b);
				dao.update(VideoAuthSearch.class, Chain.make("status", 2).add("update_time", new Date()).add("udate",
						Long.parseLong(fmt.format(new Date()))), Cnd.where("id", "=", v.getId()));

			}

		} catch (

		Exception e) {

			logger.error("", e);
		}

	}

	private void saveData(String dataid, String href, String name, String fs, String avg_like, String avg_cmt,
			String avg_rep) {
		href = href.replace("#", "");
		VideoAuth auth = dao.fetch(VideoAuth.class, Cnd.where("dataid", "=", dataid));
		String auth_url = "https://dy.feigua.cn" + href;
		if (auth == null) {
			auth = new VideoAuth();
			auth.setDataid(dataid);
			auth.setAuth_url(auth_url);
			auth.setKw_nick_name(name);
			auth.setFollower_num(this.getInt(fs));
			auth.setAvg_like_num(this.getInt(avg_like));
			auth.setAvg_cmt_num(this.getInt(avg_cmt));
			auth.setAvg_share_num(this.getInt(avg_rep));
			auth.setStatus(0);
			auth.setVideo_status(0);
			auth.setCreate_time(new Date());
			auth.setCdate(Integer.parseInt(datefmt.format(new Date())));
			try {
				dao.fastInsert(auth);
			} catch (Exception e) {
				// logger.error("", e);
				logger.error("dataid重复:" + dataid);
			}
		} else {
			dao.update(VideoAuth.class,
					Chain.make("udate", Long.parseLong(fmt.format(new Date()))).add("auth_url", auth_url),
					Cnd.where("dataid", "=", dataid));
		}
	}

	private Integer getInt(String val) {
		try {
			if (val.equals("--")) {
				return 0;
			}
			if (val.indexOf("w") > 0) {
				val = val.replace("w", "000");
			}
			if (val.indexOf(".") > 0) {
				val = val.replace(".", "");
			}
			return Integer.parseInt(val);
		} catch (Exception e) {
			logger.error("", e);
			return 0;
		}

	}
}
